package cn.uniquetech.yj;

import java.util.List;

import cn.uniquetech.util.FileUtil;
import cn.uniquetech.util.StrUtil;

public class YJUtil {

	private static String xmlStr = "";
	private static String headerStr = "\t";
	private static String tailStr = "\r\n";
	private static String entity = "";
	// 要过滤的字段
	private static String filterFields = ",iid,ccomment,adduid,adduname,adddate,edituid,edituname,editdate";
	// 主键
	private static String key = "iid";

	/**
	 * 
	 * @param packageName
	 *            包名
	 * @param tableName
	 *            表名
	 * @param colNames
	 *            字段集合
	 * @return
	 */
	public static String paraseSql(String packageName, String tableName, List<String> colNames) {

		String servicePackage = packageName + ".sqlmap";
		String capName = prefix + StrUtil.getSimpleClassName(tableName, true);
		String entityName = packageName + ".vo." + capName + entity + "VO";// +
		// "Entity";
		xmlStr = "<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\"    \"sql-map-2.dtd\">" + tailStr;
		xmlStr += "<sqlMap>" + tailStr;

		// addEntity
		xmlStr += headerStr + "<!-- 插入实体 -->" + tailStr;
		xmlStr += headerStr + "<insert id=\"" + capName + ".insert\" parameterClass=\"" + entityName + "\">" + tailStr;
		xmlStr += headerStr + " " + genInsertSqlStr(tableName, colNames) + tailStr;
		xmlStr += headerStr + "<selectKey resultClass=\"int\" keyProperty=\"iid\">" + tailStr;
		xmlStr += headerStr + "select identity_val_local() from sysibm.sysdummy1" + tailStr;
		xmlStr += headerStr + "</selectKey>" + tailStr;
		xmlStr += headerStr + "</insert>" + tailStr;

		// updateEntity
		xmlStr += headerStr + "<!-- 更新实体 -->" + tailStr;
		xmlStr += headerStr + "<update id=\"" + capName + ".update\" parameterClass=\"" + entityName + "\">" + tailStr;
		xmlStr += headerStr + " " + genUpdateSqlStr(tableName, colNames) + tailStr;
		xmlStr += headerStr + "</update>" + tailStr;

		xmlStr += headerStr + "<!-- 删除实体-->" + tailStr;
		xmlStr += headerStr + "<delete id=\"" + capName + ".delete\" parameterClass=\"" + entityName + "\">" + tailStr;
		xmlStr += headerStr + " delete from " + tableName + " where " + key + " = #" + key + "#" + tailStr;
		xmlStr += headerStr + "</delete>" + tailStr;

		// 分页查询
		xmlStr += headerStr + "<!-- 分页查询 -->" + tailStr;
		xmlStr += headerStr + "<select id=\"" + capName + ".queryDataGrid\" parameterClass=\"hashmap\" resultClass=\"" + entityName + "\">" + tailStr;
		xmlStr += headerStr + "select * from " + tableName + " order by iid desc " + tailStr;
		xmlStr += headerStr + "</select>" + tailStr;

		xmlStr += headerStr + "<select id=\"" + capName + ".queryDataGrid.count\" parameterClass=\"hashmap\" resultClass=\"int\">" + tailStr;
		xmlStr += headerStr + " select count(*) from " + tableName + tailStr;
		xmlStr += headerStr + "</select>" + tailStr;

		xmlStr += "</sqlMap>";
		FileUtil.writeFile(servicePackage, capName + ".xml", xmlStr);
		return xmlStr;
	}

	public static String genInsertSqlStr(String tableName, List<String> colNames) {
		String sqlStr = "insert into " + tableName + " (";
		String fields = "";
		String values = "";

		for (String colName : colNames) {
			if (key.equals(colName)) {
				continue;
			}
			fields += colName + ",";
			values += "#" + colName + "#,";
		}

		fields = fields.substring(0, fields.length() - 1);
		values = values.substring(0, values.length() - 1);
		sqlStr += fields + ") " + tailStr;
		sqlStr += headerStr + " values " + tailStr;
		sqlStr += headerStr + "(" + values + ")";
		return sqlStr;
	}

	public static String genUpdateSqlStr(String tableName, List<String> colNames) {
		String sqlStr = "update " + tableName + " set ";

		String fields = "";

		for (String colName : colNames) {
			if (key.equals(colName) || "adduid".equals(colName) || "adduname".equals(colName) || "adddate".equals(colName)) {
				continue;
			}
			fields += colName + "=#" + colName + "#,";
		}

		fields = fields.substring(0, fields.length() - 1);
		sqlStr += fields + "\r\n";
		sqlStr += headerStr + " where " + key + " =#" + key + "#";
		return sqlStr;
	}

	public static String sqlType2JavaType(String sqlType) {
		System.out.println("sqlType---->" + sqlType);
		if (sqlType.equalsIgnoreCase("bit")) {
			return "boolean";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "byte";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "short";
		} else if (sqlType.equalsIgnoreCase("integer")) {
			return "int";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "float";
		} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney")) {
			return "double";
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("text")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("timestamp") || sqlType.equalsIgnoreCase("date")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("image")) {
			return "Blod";
		} else {
			return "Date";
		}
	}

	public static void getAllAttrs(StringBuffer sb, List<String> colNames, List<String> colTypes) {

		for (int i = 0; i < colNames.size(); i++) {
			String colName = colNames.get(i).toLowerCase().trim();
			//if (filterFields.indexOf("," + colName) != -1) {
				//continue;
			//}
			sb.append("\tprivate " + sqlType2JavaType(colTypes.get(i)) + " " + colNames.get(i) + ";\r\n");
			sb.append(genSetGet(sqlType2JavaType(colTypes.get(i)), colNames.get(i)));
		}
	}

	public static void getFlexAttrs(StringBuffer sb, List<String> colNames, List<String> colTypes) {

		for (int i = 0; i < colNames.size(); i++) {
			String colName = colNames.get(i).toLowerCase().trim();
			//if (filterFields.indexOf("," + colName) != -1) {
				//continue;
			//}
			sb.append("\tpublic var " + colNames.get(i) + ":" + sqlType2JavaType(colTypes.get(i)) + ";\r\n");
		}
	}

	// 生成set get
	private static String genSetGet(String colType, String colName) {
		String str = "";
		String capName = captureName(colName);
		str += "public " + colType + " get" + capName + "(){return " + colName + ";}" + tailStr;
		str += "public void set" + capName + "(" + colType + " " + colName + "){this." + colName + "=" + colName + ";}" + tailStr;
		return str;
	}

	// 首字母变大
	public static String captureName(String name) {
		/*
		 * char[] cs = name.toCharArray(); cs[0] -= 32; return
		 * String.valueOf(cs);
		 */
		return name;
	}

	public static String parseEntity(String packageName, String tableName, List<String> colNames, List<String> colTypes, int[] colSizes) {
		String servicePackage = packageName + ".vo";

		StringBuffer sb = new StringBuffer();
		sb.append("package " + servicePackage + ";\r\n");
		sb.append("\r\n");
		//sb.append("import cn.uniquetech.vo.base.BaseVO;\r\n");

		// String clazz = StrUtil.initCap(tableName);
		// clazz = clazz.substring(0, clazz.length() - 1);
		String clazz = StrUtil.getSimpleClassName(tableName, true);
		sb.append("@SuppressWarnings(\"serial\")" + "\r\n");
		sb.append("public class " + clazz + entity + "VO" + " {\r\n");
		getAllAttrs(sb, colNames, colTypes);
		sb.append("}\r\n");

		FileUtil.writeFile(servicePackage, clazz + entity + "VO.java", sb.toString());
		return sb.toString();
	}

	public static String parseFlexEntity(String packageName, String tableName, List<String> colNames, List<String> colTypes, int[] colSizes) {
		String servicePackage = packageName + ".vo";

		StringBuffer sb = new StringBuffer();
		sb.append("package " + servicePackage + "" + tailStr);
		String clazz = StrUtil.getSimpleClassName(tableName, true);

		sb.append("{" + tailStr);
		//sb.append("import cn.uniquetech.vo.base.BaseVO;" + tailStr);
		sb.append("[Bindable]" + tailStr);
		sb.append("[RemoteClass(alias=\"cn.uniquetech.vo." + clazz + "VO\")]" + tailStr);
		sb.append("public class " + clazz + "VO {" + tailStr);
		getFlexAttrs(sb, colNames, colTypes);
		sb.append("}\r\n");
		sb.append("}");

		FileUtil.writeFile(packageName + ".flexvo", clazz + entity + "VO.as", sb.toString());
		return sb.toString();
	}

	// service 生成接口
	public static String parseServiceInterface(String packageName, String tableName) {
		String servicePackage = packageName + ".service";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + servicePackage + ";\r\n");
		String clazz = StrUtil.getSimpleClassName(tableName, true);
		sb.append("\r\n\r\npublic interface I" + clazz + "Service extends ISysService" + "{\r\n\r\n");
		sb.append("}\r\n");
		FileUtil.writeFile(servicePackage, "I" + clazz + "Service.java", sb.toString());
		return sb.toString();
	}

	// service 生成实现类
	public static String parseServiceClass(String packageName, String tableName) {
		String servicePackage = packageName + ".service.impl";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + servicePackage + ";\r\n\r\n");
		String clazz = StrUtil.getSimpleClassName(tableName, true);

		sb.append("import java.util.List;" + tailStr);
		sb.append("import java.util.Date;" + tailStr);
		sb.append("import javax.servlet.http.HttpSession;" + tailStr);
		sb.append("import org.springframework.web.context.request.RequestContextHolder;" + tailStr);
		sb.append("import org.springframework.web.context.request.ServletRequestAttributes;" + tailStr);
		sb.append("import cn.uniquetech.vo.UserVO;" + tailStr);
		sb.append("import cn.uniquetech.vo." + clazz + "VO;" + tailStr);
		sb.append("import cn.uniquetech.dao.I" + clazz + "Dao;" + tailStr);
		sb.append("import cn.uniquetech.ept.UQDaoException;" + tailStr);
		sb.append("import cn.uniquetech.service.I" + clazz + "Service;" + tailStr);
		sb.append("public class " + clazz + "ServiceImpl implements I" + clazz + "Service {" + tailStr);

		sb.append("private I" + clazz + "Dao dao;" + tailStr);

		sb.append("public I" + clazz + "Dao getDao() {" + tailStr);
		sb.append("return this.dao;" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public void setDao(I" + clazz + "Dao dao) {" + tailStr);
		sb.append("this.dao = dao;" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public int save(Object param) throws UQDaoException {" + tailStr);

		sb.append("HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();" + tailStr);
		sb.append("UserVO user = (UserVO) session.getAttribute(\"LoginUser\");" + tailStr);
		sb.append("if (user == null) {" + tailStr);
		sb.append("return -1;// 无法获取当前登陆用户的信息" + tailStr);
		sb.append("}" + tailStr);
		sb.append("" + clazz + "VO vo = (" + clazz + "VO) param;" + tailStr);
		sb.append("Date date = new Date();" + tailStr);
		sb.append("vo.setadddate(date);" + tailStr);
		sb.append("vo.setadduname(user.getCloginname());" + tailStr);
		sb.append("vo.setadduid(user.getIid());" + tailStr);
		sb.append("vo.seteditdate(date);" + tailStr);
		sb.append("vo.setedituid(user.getIid());" + tailStr);
		sb.append("vo.setedituname(user.getCloginname());" + tailStr);

		sb.append("return this.dao.insert(vo);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public int edit(Object param) throws UQDaoException {" + tailStr);

		sb.append("HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();" + tailStr);
		sb.append("UserVO user = (UserVO) session.getAttribute(\"LoginUser\");" + tailStr);
		sb.append("if (user == null) {" + tailStr);
		sb.append("return -1;// 无法获取当前登陆用户的信息" + tailStr);
		sb.append("}" + tailStr);
		sb.append("" + clazz + "VO vo = (" + clazz + "VO) param;" + tailStr);
		sb.append("Date date = new Date();" + tailStr);
		sb.append("vo.seteditdate(date);" + tailStr);
		sb.append("vo.setedituid(user.getIid());" + tailStr);
		sb.append("vo.setedituname(user.getCloginname());" + tailStr);

		sb.append("return this.dao.update(vo);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public int deleteItem(Object param) throws UQDaoException {" + tailStr);
		sb.append("return this.dao.delete(param);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public List<?> query(Object param) throws UQDaoException {" + tailStr);
		sb.append("return this.dao.query(param);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("@SuppressWarnings(\"rawtypes\")" + tailStr);
		sb.append("public int patchDelete(List list) throws UQDaoException {" + tailStr);
		sb.append("if (list == null || list.size() == 0) {" + tailStr);
		sb.append("return 0;" + tailStr);
		sb.append("}" + tailStr);
		sb.append("for (Object item : list) {" + tailStr);
		sb.append("deleteItem(item);" + tailStr);
		sb.append("}" + tailStr);
		sb.append("return 1;" + tailStr);
		sb.append("}" + tailStr);

		sb.append("}\r\n");
		FileUtil.writeFile(servicePackage, clazz + "ServiceImpl.java", sb.toString());
		return sb.toString();
	}

	// 生产dao
	private static String parseDaoInterface(String packageName, String tableName) {
		String servicePackage = packageName + ".dao";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + servicePackage + ";\r\n");
		String clazz = StrUtil.getSimpleClassName(tableName, true);
		sb.append("\r\n\r\npublic interface I" + clazz + "Dao extends IDao" + "{\r\n\r\n");
		sb.append("}\r\n");
		FileUtil.writeFile(servicePackage, "I" + clazz + "Dao.java", sb.toString());
		return sb.toString();
	}

	// 生产dao
	private static String parseDaoClass(String packageName, String tableName) {
		String servicePackage = packageName + ".dao.impl";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + servicePackage + ";\r\n\r\n");
		String clazz = StrUtil.getSimpleClassName(tableName, true);

		sb.append("import java.util.List;" + tailStr);
		sb.append("import cn.uniquetech.ept.UQDaoException;" + tailStr);
		sb.append("import java.util.HashMap;" + tailStr);
		sb.append("import cn.uniquetech.dao.I" + clazz + "Dao;" + tailStr);

		sb.append("@SuppressWarnings(\"rawtypes\")" + tailStr);
		sb.append("public class " + clazz + "DaoImpl extends BaseDaoImpl implements I" + clazz + "Dao {" + tailStr);
		sb.append("public List<?> query(Object param) {" + tailStr);
		sb.append("return this.getDBSqlTemplate().queryForList(\"" + tableName + ".query\", param);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public int insert(Object param) {" + tailStr);
		sb.append("return (Integer)this.getDBSqlTemplate().insert(\"" + tableName + ".insert\", param);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public int delete(Object param) {" + tailStr);
		sb.append("return (Integer)this.getDBSqlTemplate().delete(\"" + tableName + ".delete\", param);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public int update(Object param) {" + tailStr);
		sb.append("return this.getDBSqlTemplate().update(\"" + tableName + ".update\", param);" + tailStr);
		sb.append("}" + tailStr);

		sb.append("public List queryBySqlId(String sqlId, HashMap param) throws UQDaoException {" + tailStr);
		sb.append("return null;" + tailStr);
		sb.append("}" + tailStr);

		sb.append("}\r\n");
		FileUtil.writeFile(servicePackage, clazz + "DaoImpl.java", sb.toString());
		return sb.toString();
	}

	private static String parseFlexORxml(String packageName, String tableName) {
		StringBuilder sb = new StringBuilder();
		String clazz = StrUtil.getSimpleClassName(tableName, true);
		String servicePackage = packageName + ".xml";

		sb.append("<bean id=\"" + clazz + "dao\" class=\"cn.uniquetech.dao.impl." + clazz + "DaoImpl\" parent=\"BaseDao\"/>" + tailStr);
		sb.append("<bean id=\"" + clazz + "dest\" class=\"cn.uniquetech.service.impl." + clazz + "ServiceImpl\">" + tailStr);
		sb.append("<flex:remoting-destination />" + tailStr);
		sb.append("<property name=\"dao\" ref=\"" + clazz + "dao\" />" + tailStr);
		sb.append("</bean>" + tailStr);
		FileUtil.writeFile(servicePackage, clazz + "dest.xml", sb.toString());
		return sb.toString();
	}

	private static String prefix = "uq";

	public static String sc(String packageName, String tableName, List<String> colNames, List<String> colTypes, List<String> remarks, int[] colSizes) {
		String result = "";
		result += parseDaoInterface(packageName, prefix + tableName);
		result += parseDaoClass(packageName, prefix + tableName);
		result += parseServiceInterface(packageName, prefix + tableName);
		result += parseServiceClass(packageName, prefix + tableName);
		result += paraseSql(packageName, tableName, colNames);
		result += parseEntity(packageName, prefix + tableName, colNames, colTypes, colSizes);
		result += parseFlexORxml(packageName, prefix + tableName);
		result += parseFlexEntity(packageName, prefix + tableName, colNames, colTypes, colSizes);
		return result;
	}

}
